<template>
    <el-autocomplete ref="autocomplete" popper-class="el-autocomplete-suggestion"
    :fetch-suggestions="suggestions" v-model="innerValue" @select="handleSelect" hide-loading :placeholder="placeholder" />
</template>
<script>
import { debounce } from "@/utils"
export default {
    props: {
        value: [String],
        pageSize: {
            type: Number,
            default: 10
        },
        field: {
            type: String
        },
        placeholder: {
            type: String,
            default: '请选择'
        },
        remoteDataFatch: {
            type: Function,
            default: () => {
                return Function;
            },
        },
    },
    data() {
        return {
            innerValue: '',
            query: '' // 字段名
        }
    },
    watch: {
        value: {
            handler() {
                this.innerValue = this.value
            },
            immediate: true
        },
        innerValue() {
            this.$emit('input', this.innerValue)
        }
    },
    methods: {
        handleSelect(v) {
            this.$emit('input', v.value)
        },
        suggestions(queryString, cb) {
            // cb([])
            if(!this.innerValue){
                this.fetch(queryString,cb)
            }else {
                //延迟800ms再去做输入建议
                debounce(()=> this.fetch(queryString, cb), 800)()
            }
        },
        fetch(queryString, cb) {
            this.remoteDataFatch({ query: queryString, field: this.field, pageSize: this.pageSize}).then(res=>{
                if(res && res.data){
                    if(this.$refs.autocomplete.$el.contains(document.activeElement)){
                        if(res.data.length == 1 && res.data[0].label == this.innerValue){
                            //输入与提示相同就不展示了
                            cb()
                        }else {
                            cb(res.data.map(v=>{return {value: v.label}}))
                        }
                    }
                }
            })
        }
    }
}
</script>